package controllers;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.apache.commons.io.FilenameUtils;
import utils.UserRoles;
import models.Location;
import models.SolutionSubmission;
import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

@SuppressWarnings("serial")
public class AddSolutionSubmissionServlet extends HttpServlet {
	private BlobstoreService blobstoreService = BlobstoreServiceFactory
			.getBlobstoreService();

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		try{
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		String user_email = user.getEmail().toLowerCase();
        String User_Role_String = new UserRoles(user_email).toString();
        String strFile_Name = "";
       
		Date today = new java.util.Date();
		BlobKey blobKey = null;
		BlobKey	adptTeamPicKey = null;
		BlobKey	attachKey = null;
        
        
        /*
	    //Retrieve data from the request object
		SimpleDateFormat dateFormat = new SimpleDateFormat("mm/dd/yyyy");
		Date _dtImplemented = today;
		try {
			_dtImplemented = dateFormat.parse(req.getParameter("dtDate"));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		*/
		Date _dtImplemented = today;
        String _StrdtImplemented  =(String) req.getParameter("dtDate");
        if (_StrdtImplemented.length() > 0){
        	_dtImplemented = new Date(_StrdtImplemented);	
        }
	
		

		SimpleDateFormat formatNowYear = new SimpleDateFormat("yyyy");
		SimpleDateFormat formatNowMonth = new SimpleDateFormat("MMMMM");
		String sYear = formatNowYear.format( _dtImplemented);
		String sMonth = formatNowMonth.format(_dtImplemented);
		
		boolean	_hasHardSavings; //NEWLY ADDED ON AUG 29 BY SYOUDEE FOR SEARCH PURPOSE
		boolean	_hasCostAvoidance; //NEWLY ADDED ON AUG 29 BY SYOUDEE FOR SEARCH PURPOSE
		boolean	_hasOppurtunityCost; //NEWLY ADDED ON AUG 29 BY SYOUDEE FOR SEARCH PURPOSE
		String _teamLead = req.getParameter("namSolTL"); // teamLead
		String _teamMembers = req.getParameter("namSolTM"); // teamMembers
		String _namOthTM = req.getParameter("namOthTM"); // namOthTM
		String _title = req.getParameter("txtTheme");// Title;
		String _s1 = (String)req.getParameter("taProbDef");// s1
		String _s2 = (String)req.getParameter("taProbAnalysis");// s2
		String _s3 =(String) req.getParameter("taProbRootCause");// s3
		String _s4 = (String)req.getParameter("taImpSol");// s4
		String _s5 = (String)req.getParameter("taEvalRes");// s5
		String _s6 = (String)req.getParameter("taPrevRec");// s6
		String _customer = req.getParameter("cmbCustomer"); // Customer
		String _processArea = req.getParameter("cmbProcessarea"); // processArea
		String _solType = req.getParameter("cmbSolutiontype"); // solType
		String _location = req.getParameter("cmbSite"); // Location
		String Status = req.getParameter("__Click"); // Status
		
		
		_hasHardSavings = Boolean.parseBoolean(req.getParameter("hasHardSavings"));  
		_hasCostAvoidance = Boolean.parseBoolean(req.getParameter("hasCostAvoidance"));  
		_hasOppurtunityCost = Boolean.parseBoolean(req.getParameter("hasOppurtunityCost"));  
		
		//SEARCH FOR LOCATION in the LOCATION MODEL. -> ADDED BY SRVAN on sept 4
		String	LocationRegionName = "";
		String	LocationCode = "";
		Objectify ofy = ObjectifyService.begin();
		Query<Location> qq = ofy.query(Location.class).filter("LocationName", _location);
		for ( Location f : qq.fetch() ) {
			LocationRegionName = f.getLocationRegionName();
			LocationCode = f.getLocationCode();
			break;
		}

		
		//=Benefits============================================================
		String	achievedType = (String) req.getParameter("chkBenefits");
		int PrimaryBenefit =10;
		if (achievedType != null){
			 PrimaryBenefit = Integer.parseInt(achievedType);
		}
		String achievedTypeDesc = "";
		String	achievedValue = "";
		String	achievedUnits = "";
		switch (PrimaryBenefit){
				case 1: achievedTypeDesc = "Safety"; break;
				case 2: achievedTypeDesc = "Quality"; break;
				case 3: achievedTypeDesc = "Order Lead Time"; break;
				case 4: achievedTypeDesc = "Annual Production saving"; break;
				case 5: achievedTypeDesc = "Annual Material saving"; break;
				case 6: achievedTypeDesc = "Customer satisfaction"; break;
				case 7: achievedTypeDesc = "Employee engagement"; break;					
		}
		if ( achievedTypeDesc.equalsIgnoreCase("Quality")) {
			achievedValue = (String) req.getParameter("taQuality");
			achievedUnits = (String) req.getParameter("cmbQualityOptions");
			
		}else if ( achievedTypeDesc.equalsIgnoreCase("Order Lead Time"))
		{
			achievedValue = (String) req.getParameter("taDays");
			achievedUnits = "In Days";
		}
		//=====================================================================
		
		
		// HardSavings=================================================================
		String _v1 = (req.getParameter("HardSavings") == "") ? "0" : req
				.getParameter("HardSavings");
		String _v2 = (req.getParameter("CostAvoid") == "") ? "0" : req
				.getParameter("CostAvoid");
		String _v3 = (req.getParameter("OpporCost") == "") ? "0" : req
				.getParameter("OpporCost");
		float _hardSavings = 0;// hardSavings
		float _costAvoidance = 0;// costAvoidance
		float _oppurtunityCost = 0;// oppurtunityCost
		float _impDays =  0;

		_hasHardSavings = _hasCostAvoidance = _hasOppurtunityCost = false;
		
		if(_v1 != null && !_v1.equals("") ) {
			_hardSavings = Float.parseFloat(_v1);
			if( _hardSavings > 0 ){
				_hasHardSavings=true;// hardSavings
			}
		}
		
		if(_v2 != null && !_v2.equals("") ) { 
			_costAvoidance = Float.parseFloat(_v2);
			if( _costAvoidance > 0 ){
				_hasCostAvoidance=true;// costAvoidance
			}
		}
			
		if(_v3 != null && !_v3.equals("") ) { 
			_oppurtunityCost = Float.parseFloat(_v3);
			if( _oppurtunityCost > 0 ){
				_hasOppurtunityCost=true;// oppurtunityCost
			}
		}
		
		Float	annProdSavings = _hardSavings + _costAvoidance + _oppurtunityCost;
		//===================================================================================================
		
		String _tempvalues = req.getParameter("taImpTime");
		if(_tempvalues != null && !_tempvalues.equals("") ) { 
			_impDays = Float.parseFloat(_tempvalues);// impDays
		}
		
        //EXTRACT THE FILE(S) FROM THE BLOB REQUEST
        Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
        if ( blobs != null)
        {
        	//TEAM PIC BLOB
        	blobKey = blobs.get("txtupload_teampic"); 
        	if ( blobKey != null )
        	{	 
        		final BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey);  
        		long size = blobInfo.getSize();            	
        		if(size > 0)
        		{
        			adptTeamPicKey = blobKey;
        		}else{
        			//NO BLOB SELECTED - delete unnamed blob
        			blobstoreService.delete(blobKey);
        		}
        	}
        	
        	blobKey = null;
        	
        	//ATTACHMENT PIC BLOB
        	blobKey = blobs.get("txtupload_attachment"); 
        	if ( blobKey != null )
        	{	 
        		final BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey);  
        		long size = blobInfo.getSize();            	
        		if(size > 0)
        		{
        			attachKey = blobKey;
        		}else{
        			//NO BLOB SELECTED - delete unnamed blob
        			blobstoreService.delete(blobKey);
        		}
        	}
        }    
        
		SolutionSubmission newitems = new SolutionSubmission();		
		newitems.setTitle(_title);
		newitems.setDtImplemented(_dtImplemented);
		newitems.setDtShared(today);		
		newitems.setTeamLead(_teamLead);
		newitems.setTeamMembers(_teamMembers);
		newitems.setOtherTeamMembers(_namOthTM);
		newitems.setCustomer(_customer);
		newitems.setLocation(_location);
		newitems.setLocationCode(LocationCode);
		newitems.setLocationRegionName(LocationRegionName);
		newitems.setProcessArea(_processArea);
		newitems.setSolType(_solType);
		newitems.setTeamPicKey(adptTeamPicKey);
		newitems.setS1(_s1);
		newitems.setS2(_s2);
		newitems.setS3(_s3);
		newitems.setS4(_s4);
		newitems.setS5(_s5);
		newitems.setS6(_s6);
		newitems.setAchievedType(achievedType);
		newitems.setAchievedTypeDesc(achievedTypeDesc);
		newitems.setAchievedValue(achievedValue);
		newitems.setAchievedUnits(achievedUnits);
		newitems.setHardSavings(_hardSavings);
		newitems.setCostAvoidance(_costAvoidance);
		newitems.setOppurtunityCost(_oppurtunityCost);
		newitems.setAnnProdSavings(annProdSavings);
		newitems.setHasHardSavings(_hasHardSavings);
		newitems.setHasCostAvoidance(_hasCostAvoidance);
		newitems.setHasOppurtunityCost(_hasOppurtunityCost);
		newitems.setImpDays(_impDays);
		newitems.setAttachKey(attachKey);
		newitems.setStatus(Status);
		newitems.setsYear(sYear);
		newitems.setsMonth(sMonth);		
		newitems.setSubmittedBY(user_email);
		newitems.setSubmittedON(today);	
		
		
		newitems.setModifiedBY(user_email);
		newitems.setModifiedON(today);
		// default =========================================== false
		newitems.setMpsCandidate(false);
		newitems.setNominateSolution(false);
		newitems.setBestOfBest(false);
		newitems.setBestOfRegion(false);
		newitems.setHasExpert(false);
		newitems.setCountExpert(0);
        //========================================================		
		
		ofy.put(newitems);
		
		
		//NEW CODE TO ADD SOLUTION CODE WITH REGION CODE
		Long solID = newitems.getSolID();
		String NewSiteCode = LocationCode + solID; 
		SolutionSubmission edititem = ofy.get(SolutionSubmission.class, solID);		
		edititem.setSolCode(NewSiteCode);
		ofy.put(edititem);
		
		UserActionsConnect.AddAction(user_email, "AddSolutionSubmissionServlet", "Inserted solID =" + newitems.getSolID(), "New SolutionSubmission, Blob Filename: " + strFile_Name, User_Role_String, today);
		resp.sendRedirect("/modules/default/mysolution.jsp");
        //RequestDispatcher rd = req.getRequestDispatcher("/modules/default/mysolution.jsp");
        //rd.forward(req, resp);  
		}catch(Exception ee){}
	}
} // Class End
